package moe.oil.db.service;

import lombok.Setter;
import moe.oil.db.entity.Feedback;
import moe.oil.db.repo.FeedbackRepo;
import moe.oil.dto.feedback.FeedbackDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
@Setter(onMethod_ = @Autowired)
public class FeedbackService implements BaseService {

    FeedbackRepo feedBackRepo;

    //添加反馈
    public Optional<FeedbackDTO> insertFeedback(FeedbackDTO feedbackDTO) {
        return
                Optional.of(
                        feedBackRepo.save(new Feedback(feedbackDTO))
                                .convert());
    }


    //通过 id 获取反馈
    public Optional<FeedbackDTO> selectFeedbackById(Long id) {
        return Optional.of(feedBackRepo.findById(id).orElseThrow(() -> new RuntimeException("not found")).convert());
    }

    //得到所有反馈
    public List<FeedbackDTO> selectAllFeedback(PageRequest pageRequest) {
        return
                StreamSupport
                        .stream(feedBackRepo.findAll(pageRequest)
                                .spliterator(), false)
                        .map(Feedback::convert)
                        .collect(Collectors.toList());
    }

    //按 id 删除反馈
    public int deleteFeedbackById(Long id) {
        return feedBackRepo.deleteByFeedbackId(id);
    }

    //通过 id 更新反馈
    public Optional<FeedbackDTO> updateFeedback(FeedbackDTO feedbackDTO) {
        return Optional.of(feedBackRepo.save(new Feedback(feedbackDTO)).convert());
    }
}